import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null,
    isLoggedIn: false,
    permissions: [],
    token: localStorage.getItem('token') || ''
  }),

  getters: {
    userName: (state) => state.user?.name || '游客',
    hasPermission: (state) => {
      return (permission) => state.permissions.includes(permission)
    }
  },

  actions: {
    async login(credentials) {
      try {
        // 模拟登录API调用
        const response = await this.mockLogin(credentials)
        
        if (response.success) {
          this.token = response.token
          this.user = response.user
          this.isLoggedIn = true
          this.permissions = response.user.permissions || []
          
          localStorage.setItem('token', response.token)
          localStorage.setItem('userInfo', JSON.stringify(response.user))
          
          return { success: true }
        } else {
          return { success: false, message: response.message }
        }
      } catch (error) {
        return { success: false, message: '登录失败，请重试' }
      }
    },

    logout() {
      this.user = null
      this.isLoggedIn = false
      this.permissions = []
      this.token = ''
      
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    },

    setUserInfo(userInfo) {
      this.user = userInfo
      this.isLoggedIn = true
      this.token = userInfo.token
      this.permissions = userInfo.permissions || []
      
      localStorage.setItem('token', userInfo.token)
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },

    updateUser(userData) {
      if (this.isLoggedIn) {
        this.user = { ...this.user, ...userData }
      }
    },

    // 更新个人信息
    async updateProfile(profileData) {
      try {
        // 模拟API调用
        const response = await this.mockUpdateProfile(profileData)
        
        if (response.success) {
          this.user = { ...this.user, ...profileData }
          localStorage.setItem('userInfo', JSON.stringify(this.user))
          return { success: true }
        } else {
          return { success: false, message: response.message }
        }
      } catch (error) {
        return { success: false, message: '更新失败，请重试' }
      }
    },

    // 修改密码
    async updatePassword(passwordData) {
      try {
        // 模拟API调用
        const response = await this.mockUpdatePassword(passwordData)
        return response
      } catch (error) {
        return { success: false, message: '密码修改失败，请重试' }
      }
    },

    initUserInfo() {
      const savedUserInfo = localStorage.getItem('userInfo')
      if (savedUserInfo && this.token) {
        this.user = JSON.parse(savedUserInfo)
        this.isLoggedIn = true
        this.permissions = this.user.permissions || []
      }
    },

    // 模拟登录API
    mockLogin(credentials) {
      return new Promise((resolve) => {
        setTimeout(() => {
          if (credentials.username === 'admin' && credentials.password === '123456') {
            resolve({
              success: true,
              token: 'mock-jwt-token-' + Date.now(),
              user: {
                id: 1,
                username: 'admin',
                name: '系统管理员',
                email: 'admin@example.com',
                phone: '13888888888',
                role: 'admin',
                department: '信息技术部',
                position: '技术总监',
                employeeId: 'EMP001',
                bio: '负责公司整体技术架构和团队管理',
                lastLoginTime: new Date().toISOString(),
                permissions: ['permission:manage', 'organization:manage', 'assessment:manage']
              }
            })
          } else {
            resolve({
              success: false,
              message: '用户名或密码错误'
            })
          }
        }, 1000)
      })
    },

    // 模拟更新个人信息API
    mockUpdateProfile(profileData) {
      return new Promise((resolve) => {
        setTimeout(() => {
          // 模拟成功更新
          resolve({
            success: true,
            message: '个人信息更新成功'
          })
        }, 800)
      })
    },

    // 模拟修改密码API
    mockUpdatePassword(passwordData) {
      return new Promise((resolve) => {
        setTimeout(() => {
          // 简单验证当前密码
          if (passwordData.currentPassword === '123456') {
            resolve({
              success: true,
              message: '密码修改成功'
            })
          } else {
            resolve({
              success: false,
              message: '当前密码不正确'
            })
          }
        }, 800)
      })
    }
  }
})
